clear
insheet using "$sourcedatadir/uk/ukincumbency.csv"
save "$gendatadir/uk_incumbency.dta", replace

clear
insheet using "$sourcedatadir/uk/IFS income data bn19figs.csv"

merge 1:1 year using "$gendatadir/uk_incumbency.dta"
drop _merge
drop if year == .
drop if country == ""

//// Attempt to construct a measure of T5 share from the full distribution
// Assume that the bottom percentile is a percentage of the 5th percentile income. 
gen inc_pc00 = 0.75 * inc_pc05_bhc
// Construct bottom-95 mean income
egen inc_b95_mean = rowmean(inc_pc00 inc_pc05_bhc inc_pc10_bhc inc_pc15_bhc inc_pc20_bhc inc_pc25_bhc inc_pc30_bhc inc_pc35_bhc inc_pc40_bhc inc_pc45_bhc inc_pc50_bhc inc_pc55_bhc inc_pc60_bhc inc_pc65_bhc inc_pc70_bhc inc_pc75_bhc inc_pc80_bhc inc_pc85_bhc inc_pc90_bhc inc_pc95_bhc)
// Construct t5 mean income using b95
gen inc_t5_mean = (inc_mean_bhc - inc_b95_mean * 0.95)/0.05
// Calculate t5 share
gen inc_t5_share = (inc_t5_mean * 0.05)/inc_mean_bhc

gen inc_ul_quin1 = inc_pc20_bhc
gen inc_ul_quin2 = inc_pc40_bhc
gen inc_ul_quin3 = inc_pc60_bhc
gen inc_ul_quin4 = inc_pc80_bhc
gen inc_ll_95    = inc_pc95_bhc
rename inc_mean_bhc inc_mean
gen inc_meanb80  = (inc_ul_quin1 + inc_ul_quin2 + inc_ul_quin3 + inc_ul_quin4)/4
gen inc_median   = inc_pc50_bhc

drop inc_pc*

replace country = "UK"
merge 1:1 country year using "$gendatadir/wtid_processed.dta", keep(master match)
drop _merge

tsset year
sort year

// Generate growth rates for the various income groups
gen inc_ul_quin1_g1 = (inc_ul_quin1 - l.inc_ul_quin1)/l.inc_ul_quin1
gen inc_ul_quin2_g1 = (inc_ul_quin2 - l.inc_ul_quin2)/l.inc_ul_quin2
gen inc_ul_quin3_g1 = (inc_ul_quin3 - l.inc_ul_quin3)/l.inc_ul_quin3
gen inc_ul_quin4_g1 = (inc_ul_quin4 - l.inc_ul_quin4)/l.inc_ul_quin4
gen inc_mean_g1     = (inc_mean - l.inc_mean)/l.inc_mean
gen inc_median_g1   = (inc_median - l.inc_median)/l.inc_median
gen inc_meanb80_g1  = (inc_meanb80 - l.inc_meanb80)/l.inc_meanb80
gen inc_ll_95_g1    = (inc_ll_95    - l.inc_ll_95)/l.inc_ll_95

rename election_date election_date_str

generate election_date = date(election_date_str,"DMY", 2015)
format election_date %td


gen election_year_weight = doy(election_date)/365
foreach varn of varlist inc_* wtid_incgrowth* share* {
  gen orig_`varn' = `varn'
  replace `varn' = election_year_weight * orig_`varn' + (1-election_year_weight) * l.orig_`varn' if election_year_weight != .
  *replace `varn' = l.`varn' if halfyear(election_date) == 1
}


keep year year_original country inc_* incumbent_* election_date n_elections wtid* share*

save "$gendatadir/uk_incomeprocessed.dta", replace
